//
//  main.m
//  glfwdemo005-light
//
//  Created by 王洪飞 on 2024/6/10.
//

#import <Foundation/Foundation.h>
#include <glad/glad.h>
#import "glfw3.h"
#include "shader_s.hpp"
#include "stb_image.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#import "Camera.hpp"

// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;

// camera
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
float lastX = SCR_WIDTH / 2.0f;
float lastY = SCR_HEIGHT / 2.0f;
bool firstMouse = true;

// timing
float deltaTime = 0.0f;
float lastFrame = 0.0f;

// lighting
glm::vec3 lightPos(1.2f, 1.0f, 2.0f);

void framebuffer_size_callback(GLFWwindow *window, int width, int height){
    glViewport(0,0,width, height);
}
void processInput(GLFWwindow *window){
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
        glfwSetWindowShouldClose(window, true);
    }
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
            camera.ProcessKeyboard(FORWARD, deltaTime);
        if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
            camera.ProcessKeyboard(BACKWARD, deltaTime);
        if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
            camera.ProcessKeyboard(LEFT, deltaTime);
        if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
            camera.ProcessKeyboard(RIGHT, deltaTime);
}

// glfw: whenever the mouse moves, this callback is called
// -------------------------------------------------------
void mouse_callback(GLFWwindow* window, double xposIn, double yposIn)
{
    float xpos = static_cast<float>(xposIn);
    float ypos = static_cast<float>(yposIn);

    if (firstMouse)
    {
        lastX = xpos;
        lastY = ypos;
        firstMouse = false;
    }

    float xoffset = xpos - lastX;
    float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top

    lastX = xpos;
    lastY = ypos;

    camera.ProcessMouseMovement(xoffset, yoffset);
}

// glfw: whenever the mouse scroll wheel scrolls, this callback is called
// ----------------------------------------------------------------------
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
    camera.ProcessMouseScroll(static_cast<float>(yoffset));
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        glfwInit();
//        主版本号
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
//        次版本号
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
        
//        创建一个窗口对象,这个窗口存放所有和窗口相关的数据,而且被glfw的其他函数频繁的用到
        GLFWwindow *window = glfwCreateWindow(800, 600, "learn opengl", NULL, NULL);
        if (window == NULL) {
            std::cout << "failed to create glfw window" << std::endl;
            glfwTerminate();
            return  -1;
        }
        glfwMakeContextCurrent(window);
        glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
        glfwSetCursorPosCallback(window, mouse_callback);
        glfwSetScrollCallback(window, scroll_callback);
//        glad是用来管理OpenGL的函数指针的,所有调用任何OpenGL的函数之前先初始化glad
        if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
            std::cout << "failed to initialize glad" << std::endl;
            return -1;
        }
        // configure global opengl state
          // -----------------------------
          glEnable(GL_DEPTH_TEST);
        glDepthFunc(GL_LESS);
 
        
        Shader lightingShader("/Users/wanghongfei/Documents/opengles-demo/glfwdemo005-light/glfwdemo005-light/colorv.vs", "/Users/wanghongfei/Documents/opengles-demo/glfwdemo005-light/glfwdemo005-light/colorf.fs"); // you
        
        
        Shader lightCubeShader("/Users/wanghongfei/Documents/opengles-demo/glfwdemo005-light/glfwdemo005-light/3.3.shader.vs", "/Users/wanghongfei/Documents/opengles-demo/glfwdemo005-light/glfwdemo005-light/3.3.shader.fs"); // you
        
        float vertices[] = {
                -0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f, -0.5f,
                 0.5f,  0.5f, -0.5f,
                 0.5f,  0.5f, -0.5f,
                -0.5f,  0.5f, -0.5f,
                -0.5f, -0.5f, -0.5f,

                -0.5f, -0.5f,  0.5f,
                 0.5f, -0.5f,  0.5f,
                 0.5f,  0.5f,  0.5f,
                 0.5f,  0.5f,  0.5f,
                -0.5f,  0.5f,  0.5f,
                -0.5f, -0.5f,  0.5f,

                -0.5f,  0.5f,  0.5f,
                -0.5f,  0.5f, -0.5f,
                -0.5f, -0.5f, -0.5f,
                -0.5f, -0.5f, -0.5f,
                -0.5f, -0.5f,  0.5f,
                -0.5f,  0.5f,  0.5f,

                 0.5f,  0.5f,  0.5f,
                 0.5f,  0.5f, -0.5f,
                 0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f,  0.5f,
                 0.5f,  0.5f,  0.5f,

                -0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f,  0.5f,
                 0.5f, -0.5f,  0.5f,
                -0.5f, -0.5f,  0.5f,
                -0.5f, -0.5f, -0.5f,

                -0.5f,  0.5f, -0.5f,
                 0.5f,  0.5f, -0.5f,
                 0.5f,  0.5f,  0.5f,
                 0.5f,  0.5f,  0.5f,
                -0.5f,  0.5f,  0.5f,
                -0.5f,  0.5f, -0.5f,
            };
            // first, configure the cube's VAO (and VBO)
            unsigned int VBO, cubeVAO;
            glGenVertexArrays(1, &cubeVAO);
            glGenBuffers(1, &VBO);

            glBindBuffer(GL_ARRAY_BUFFER, VBO);
            glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

            glBindVertexArray(cubeVAO);

            // position attribute
            glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
            glEnableVertexAttribArray(0);

            // second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube)
            unsigned int lightCubeVAO;
            glGenVertexArrays(1, &lightCubeVAO);
            glBindVertexArray(lightCubeVAO);

            // we only need to bind to the VBO (to link it with glVertexAttribPointer), no need to fill it; the VBO's data already contains all we need (it's already bound, but we do it again for educational purposes)
            glBindBuffer(GL_ARRAY_BUFFER, VBO);

            glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
            glEnableVertexAttribArray(0);
        
        while (!glfwWindowShouldClose(window)) {
            // per-frame time logic
                   // --------------------
           float currentFrame = static_cast<float>(glfwGetTime());
           deltaTime = currentFrame - lastFrame;
           lastFrame = currentFrame;
            
            // input
            processInput(window);
            
            glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            
            // be sure to activate shader when setting uniforms/drawing objects
                    lightingShader.use();
                    lightingShader.setVec3("objectColor", 1.0f, 0.5f, 0.31f);
                    lightingShader.setVec3("lightColor",  1.0f, 1.0f, 1.0f);
            
            // view/projection transformations
               glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
               glm::mat4 view = camera.GetViewMatrix();
               lightingShader.setMat4("projection", projection);
               lightingShader.setMat4("view", view);
            // world transformation
                  glm::mat4 model = glm::mat4(1.0f);
                  lightingShader.setMat4("model", model);

                  // render the cube
                  glBindVertexArray(cubeVAO);
                  glDrawArrays(GL_TRIANGLES, 0, 36);
            
            
            // also draw the lamp object
                    lightCubeShader.use();
                    lightCubeShader.setMat4("projection", projection);
                    lightCubeShader.setMat4("view", view);
                    model = glm::mat4(1.0f);
                    model = glm::translate(model, lightPos);
                    model = glm::scale(model, glm::vec3(0.2f)); // a smaller cube
                    lightCubeShader.setMat4("model", model);

                    glBindVertexArray(lightCubeVAO);
                    glDrawArrays(GL_TRIANGLES, 0, 36);
            
            glfwPollEvents();
            glfwSwapBuffers(window);
        }
    }
    return 0;
}
